import { specslist, specscount } from "@/request/api"
interface StateSpecs {
    specsList: Array<object>,
    size: Number,
    page: Number,
    count: Number
}

const state = {
    specsList: [],
    size: 2,
    page: 1,
    count: 7,
}

const mutations = {
    // 修改列表
    SPECS_LIST(state: StateSpecs, payload: any) {
        state.specsList = payload;
    },
    // 修改总条数
    SPECS_COUNT(state: StateSpecs, payload: any) {
        state.count = payload;
        console.log(state.count, 11111111, state.size);

    },
    // 修改页码
    CHANGE_PAGE(state: StateSpecs, payload: Number) {
        state.page = payload;
    }
}

const actions = {
    // 获取商品属性列表
    getSpecsListActions(context: any) {
        specslist({
            size: context.state.size,
            page: context.state.page
        }).then((res: any) => {
            if (res.code == 200) {
                // 删除除了第一页的最后一条数据会显示暂无数据 所以在page不等于1是 并且返回的数据为null时 让page-1
                let list = res.list ? res.list : null

                if (context.state.page != 1 && list == null) {

                    context.dispatch('changePageActions', context.state.page - 1)

                }
                context.commit('SPECS_LIST', res.list)
            }
        })
    },
    // 获取总条数
    getCountActions(context: any) {
        specscount().then((res: any) => {
            if (res.code == 200) {
                context.commit('SPECS_COUNT', res.list[0].total)
            }
        })
    },
    // 切换页码 渲染视图
    changePageActions(context: any, payload: number) {
        context.commit('CHANGE_PAGE', payload);
        // 调用列表
        context.dispatch('getSpecsListActions')
    }
}

const getters = {
    // 返回数据列表
    getSpecsList(state: StateSpecs) {
        return state.specsList
    },
    // 返回每页展示几条数据
    getSize(state: StateSpecs) {
        return state.size
    },
    // 返回总条数
    getCount(state: StateSpecs) {
        return state.count
    },

}

export default {
    state,
    mutations,
    actions,
    getters,
    namespaced: true
}